package com.heima.user.service.impl;

import com.heima.common.constants.user.UserRelationConstants;
import com.heima.common.exception.CustException;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.AppThreadLocalUtils;
import com.heima.model.user.dtos.UserRelationDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.service.ApUserRelationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;


public class ApUserRelationServiceImpl implements ApUserRelationService {

    @Autowired
    RedisTemplate<String, String> redisTemplate;

    @Override
    public ResponseResult follow(UserRelationDto dto) {
        //1.检查参数  注解检查@validate
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }
        Integer loginId = user.getId();
        Integer authorApUserId = dto.getAuthorApUserId();
        //判断 自己 不可以关注自己
        if (loginId.equals(authorApUserId)) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW, "不可以关注自己");
        }
        //2.判断是否关注过
        //参数1:key  参数2: 集合中的元素
        Double score = redisTemplate.opsForZSet()
                .score(UserRelationConstants.FOLLOW_LIST + loginId, String.valueOf(authorApUserId));
        if (score != null && dto.getOperation().intValue() == 0) {
            CustException.cust(AppHttpCodeEnum.DATA_EXIST, "您已关注过,请勿重复关注");
        }
        redisTemplate.multi();//开启事物
        try {
            if (dto.getOperation() == 0) {
                //3.如果是关注
                redisTemplate.opsForZSet()
                        .add(UserRelationConstants.FOLLOW_LIST + loginId,
                                String.valueOf(authorApUserId),
                                System.currentTimeMillis());
                redisTemplate.opsForZSet()
                        .add(UserRelationConstants.FANS_LIST+authorApUserId,
                                String.valueOf(loginId),
                                System.currentTimeMillis());

            } else {
                //4.如果是取关
                redisTemplate.opsForZSet()
                        .remove(UserRelationConstants.FOLLOW_LIST + loginId,
                                String.valueOf(authorApUserId));
                redisTemplate.opsForZSet()
                        .remove(UserRelationConstants.FANS_LIST+authorApUserId,
                                String.valueOf(loginId));
            }
            redisTemplate.exec();//提交事物
            return ResponseResult.okResult();
        } catch (Exception e) {
            e.printStackTrace();
            redisTemplate.discard(); //回滚事物
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR, "服务器异常");
        }

    }
}
